import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import router from '@/router'

// 认证状态管理
export const useAuthStore = defineStore('auth', () => {
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const token = ref(localStorage.getItem('token') || '')

  const isAuthenticated = computed(() => !!token.value)

  // 设置认证信息
  function setAuth(userData: any, tokenValue: string) {
    user.value = userData
    token.value = tokenValue
    localStorage.setItem('user', JSON.stringify(userData))
    localStorage.setItem('token', tokenValue)
    
    // 设置axios默认headers
    axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  // 清除认证信息
  function clearAuth() {
    user.value = null
    token.value = ''
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
  }

  // 登录
  async function login(email: string, password: string) {
    try {
      const { data } = await axios.post('/api/users/login', { email, password })
      setAuth(data, data.token)
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请稍后再试' 
      }
    }
  }

  // 注册
  async function register(username: string, email: string, password: string) {
    try {
      const { data } = await axios.post('/api/users', { username, email, password })
      setAuth(data, data.token)
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '注册失败，请稍后再试' 
      }
    }
  }

  // 登出
  function logout() {
    clearAuth()
    router.push('/login')
  }

  // 初始化axios的认证头部
  if (token.value) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    register,
    logout
  }
}) 